import React from 'react'
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqDeleteImg } from '../../../api';

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default class PicturesWall extends React.Component {
  state = {
    previewVisible: false,//标识是否显示大图预览
    previewImage: '',//预览的图片url
    fileList: [],
  }
  

  //隐藏Modal
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    })
  }

  handleChange = ({ fileList }) =>{
    this.setState({ fileList })
  }

  removeImage=(file)=>{
    console.log(file)
    if(this.props.type==='modify'){
      let arr=this.props._imgs
      this.setState({fileList:arr.splice(arr.findIndex(i=>i===file.thumbUrl),1)})
      this.removeImg({id:this.props._id,path:file.thumbUrl})
      return true
    }
    if(!file.response.file.path){
      return true
    }
    return this.removeImg(file.response.file.path)
  }

  removeImg=async (params)=>{
    let res=await reqDeleteImg(params)
    return res.code===200
  }

  componentDidMount(){
    const {type,_imgs}=this.props
    if(type==='modify')this.setState({fileList:_imgs.map((i,index)=>({name:i,percent:100,thumbUrl:i,url:i,uid:i+index}))})
  }

  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action="http://localhost:3333/upload"//上传地址 https://sm.ms/api/v2/upload  http://localhost:3333/upload  https://tu.my/api/upload
          accept='image/*'//指定上传文件类型
          listType="picture-card"//展示类型
          name='file'//请求参数名
          fileList={fileList}//已上传图片文件对象数组
          onPreview={this.handlePreview}//
          onChange={this.handleChange}
          onRemove={this.removeImage}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}